package com.asseco.mio.codex.controllers;

import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.asseco.mio.codex.ResponsibilityReason;
import com.asseco.persistence.service.HibernateUtil;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.Constants;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.web.bind.annotation.RequestParam;




@Controller
@RequestMapping("/responsibilityreason*")
public class ResponsibilityReasonController {
    private GenericManager<ResponsibilityReason, String> responsibilityReasonManager;

    @Autowired
    public void setResponsibilityReasonManager(@Qualifier("responsibilityReasonManager") GenericManager<ResponsibilityReason, String> responsibilityReasonManager) {
        this.responsibilityReasonManager = responsibilityReasonManager;
    }

public List getResponsibilityReasons(String query){
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria = session.createCriteria(ResponsibilityReason.class)
                .add(Restrictions.or(Restrictions.like("name", "%"+query+"%"), Restrictions.or(Restrictions.like("code", "%"+query+"%"), Restrictions.like("descr", "%"+query+"%"))));

        List result = criteria.list();
        session.getTransaction().commit();
        return result;
    }
   @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView handleRequest(@RequestParam(required = false, value = "q") String query, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
               if (query != null) {
            query = java.net.URLDecoder.decode( query, "UTF-8");
        }
                String userString = request.getRemoteUser();
           try{     if (!request.isUserInRole(Constants.ADMIN_ROLE)) throw new Exception("");

           }catch (Exception e){

               response.sendRedirect("/MIO/mainMenu");
           }
        return new ModelAndView("responsibilityreason", "responsibilityReasonList", getResponsibilityReasons(query));
    }
}
